package com.bringspring.system.base.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bringspring.common.base.MailAccount;
import com.bringspring.common.model.login.BaseSystemInfo;
import com.bringspring.common.util.*;
import com.bringspring.system.base.entity.EmailConfigEntity;
import com.bringspring.system.base.entity.SysConfigEntity;
import com.bringspring.system.base.exception.BaseException;
import com.bringspring.system.base.mapper.SysConfigMapper;
import com.bringspring.system.base.model.systemconfig.QyChatModel;
import com.bringspring.system.base.service.SysConfigService;
import com.bringspring.system.base.util.Pop3Util;
import com.bringspring.system.base.util.SmtpUtil;
import com.bringspring.system.external.bean.WeComModel;
import com.bringspring.system.external.config.mutil.WxCpConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.bringspring.system.external.constant.WxCpSysConfigConsts.WECOM_KEY_NAME;

/**
 * 系统配置
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月27日 上午9:18
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfigEntity> implements SysConfigService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private Pop3Util pop3Util;
    @Autowired
    WxCpConfiguration wxCpConfiguration;

    @Override
    public List<SysConfigEntity> getList() {
        List<SysConfigEntity> list =new ArrayList<>();
        String cacheKey = cacheKeyUtil.getSystemInfo();
        if (redisUtil.exists(cacheKey)) {
            list = JsonUtil.getJsonToList(String.valueOf(redisUtil.getString(cacheKey)), SysConfigEntity.class);
        } else {
            QueryWrapper<SysConfigEntity> queryWrapper = new QueryWrapper<>();
            list = this.list(queryWrapper);
            redisUtil.insert(cacheKey, JsonUtil.getObjectToString(list));
        }
        return list;
    }

    /**
     * 根据分类获取对应的配置
     * @param category 配置分类
     * @return
     * @throws BaseException
     */
    public Map<String, String> getConfigsByCategory(String category) throws BaseException {
        if (StringUtils.isEmpty(category)) {
            throw new BaseException("分类不能为空");
        }
        List<SysConfigEntity> list = this.getList();
        list= list.stream().filter(config -> config.getCategory().equals(category)).collect(Collectors.toList());
        Map<String, String> objModel = new HashMap<>(16);
        for (SysConfigEntity entity : list) {
            objModel.put(entity.getKeyName(), entity.getKeyValue());
        }
        return objModel;
    }

    /**
     * 获取系统地址
     * @param terminal 终端：app:手机端，pc:电脑端
     * @return
     * @throws BaseException
     */
    @Override
    public String getSystemAddress(String terminal) throws BaseException {
        if ("pc".equals(terminal)) {
            // PC端跳转路径
            String sysComputerUrl = this.getConfigByKeyName("sysComputerUrl").getKeyValue();
            int index = sysComputerUrl.indexOf('#');  // 查找井号的索引
            if (index != -1) {  // 如果找到了井号
                sysComputerUrl = sysComputerUrl.substring(0, index);  // 截取井号之前的内容
            }
            return sysComputerUrl;
        } else {
            // app端跳转路径
            String sysMobileUrl = this.getConfigByKeyName("sysMobileUrl").getKeyValue();
            int index = sysMobileUrl.indexOf('#');  // 查找井号的索引
            if (index != -1) {  // 如果找到了井号
                sysMobileUrl = sysMobileUrl.substring(0, index);  // 截取井号之前的内容
            }
            return sysMobileUrl;
        }
    }

    /**
     *
     * @param keyName
     * @return
     * @throws BaseException
     */
    public SysConfigEntity getConfigByKeyName(String keyName) throws BaseException{
        List<SysConfigEntity> list = this.getList();
        SysConfigEntity configEntity= list.stream().filter(config ->StringUtils.isNotEmpty(config.getKeyName())&&config.getKeyName().equals(keyName)).findFirst().orElse(null);
        return configEntity;
    }

    @Override
    public List<QyChatModel> getQyChatModelList() throws BaseException{
        List<QyChatModel> resultList = new ArrayList<>();
        SysConfigEntity weComInfo = this.getConfigByKeyName(WECOM_KEY_NAME);
        if (ObjectUtil.isNotEmpty(weComInfo) && StringUtils.isNotEmpty(weComInfo.getKeyValue())) {
            String keyValue = weComInfo.getKeyValue();
            List<WeComModel> listModel = JsonUtil.getJsonToList(keyValue, WeComModel.class);
            // 忽略"qyhCorpSecret","qyhAgentSecret"属性的拷贝
            CopyOptions options = CopyOptions.create().setIgnoreProperties("qyhCorpSecret","qyhAgentSecret","token","encodingAESKey");
            if (CollectionUtil.isNotEmpty(listModel)) {
                listModel.forEach(item -> {
                    WeComModel weComModel = new WeComModel();
                    BeanUtil.copyProperties(item, weComModel, options);
                    resultList.add(weComModel);
                });
            }

        }
        return resultList;
    }

    @Override
    public BaseSystemInfo getSysInfo() {
        Map<String, String> objModel = new HashMap<>(16);
        List<SysConfigEntity> list = this.getList();
        for (SysConfigEntity entity : list) {
            objModel.put(entity.getKeyName(), entity.getKeyValue());
        }
        BaseSystemInfo baseSystemInfo = JsonUtil.getJsonToBean(objModel, BaseSystemInfo.class);
        return baseSystemInfo;
    }
    @Override
    public QyChatModel getQyChatInfo() throws BaseException {
        Map<String, String> qyhConfig = this.getConfigsByCategory("QYHConfig");
        QyChatModel qyChatModel = JsonUtil.getJsonToBean(qyhConfig, QyChatModel.class);
        return qyChatModel;
    }

    @Override
    @DSTransactional
    public void saveBatch(List<SysConfigEntity> entitys,String category) throws BaseException {
        if (StringUtils.isNotEmpty(category)) {
            String cacheKey = cacheKeyUtil.getSystemInfo();
            redisUtil.remove(cacheKey);
            this.deleteByCategory(category);
            for (SysConfigEntity entity: entitys) {
                entity.setCategory(category);
                this.baseMapper.insert(entity);
            }
        }else {
            throw new BaseException("空分类不允许保存");
        }
        this.getList();
        if ("WeComConfig".equals(category)) {
            // 企业微信多实例配置重新初始化
            wxCpConfiguration.initServices();
        }
    }
    @DSTransactional
    public boolean save(SysConfigEntity sysConfigEntity) {
        this.deleteByKeyName(sysConfigEntity.getKeyName());
        sysConfigEntity.setId(RandomUtil.uuId());
        this.baseMapper.insert(sysConfigEntity);
        this.getList();
        return false;
    }
    @Override
    public void deleteByCategory(String category){
        QueryWrapper<SysConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysConfigEntity::getCategory, category);
        this.baseMapper.delete(queryWrapper);
    }
    @Override
    public void deleteByKeyName(String keyName){
        QueryWrapper<SysConfigEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysConfigEntity::getKeyName, keyName);
        this.baseMapper.delete(queryWrapper);
    }
    @Override
    public String checkMainLogin(EmailConfigEntity configEntity) {
        MailAccount mailAccount = new MailAccount();
        mailAccount.setAccount(configEntity.getAccount());
        mailAccount.setPassword(configEntity.getPassword());
        mailAccount.setPop3Host(configEntity.getPop3Host());
        mailAccount.setPop3Port(configEntity.getPop3Port());
        mailAccount.setSmtpHost(configEntity.getSmtpHost());
        mailAccount.setSmtpPort(configEntity.getSmtpPort());
        if ("1".equals(String.valueOf(configEntity.getEmailSsl()))) {
            mailAccount.setSsl(true);
        } else {
            mailAccount.setSsl(false);
        }
        if (mailAccount.getSmtpHost() != null) {
            return SmtpUtil.checkConnected(mailAccount);
        }
        if (mailAccount.getPop3Host() != null) {
            return pop3Util.checkConnected(mailAccount);
        }
        return "false";
    }

    @Override
    public List<SysConfigEntity> getConfigListByCategory(String category) throws BaseException{
        if (StringUtils.isEmpty(category)) {
            throw new BaseException("分类不能为空");
        }
        List<SysConfigEntity> list = this.getList();
        list= list.stream().filter(config -> config.getCategory().equals(category)).collect(Collectors.toList());
        return list;
    }


}
